package com.yzh.zhipu.session.impl;

import com.yzh.zhipu.ChatGlmApi;
import com.yzh.zhipu.executor.Executor;
import com.yzh.zhipu.interceptor.ChatGlmInterceptor;
import com.yzh.zhipu.model.vo.Model;
import com.yzh.zhipu.session.Configuration;
import com.yzh.zhipu.session.ChatGlmSession;
import com.yzh.zhipu.session.ChatGlmSessionFactory;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class ChatGlmSessionFactoryImpl implements ChatGlmSessionFactory {
    private Configuration configuration;

    public ChatGlmSessionFactoryImpl(Configuration configuration) {
        this.configuration = configuration;

    }

    @Override
    public ChatGlmSession openSession() {
        // 1.日志配置
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor().setLevel(configuration.getLevel());
        
        // 2.创建Http客户端
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectionPool(new ConnectionPool(10, 60, TimeUnit.MINUTES))
                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new ChatGlmInterceptor(configuration))
                .connectTimeout(configuration.getConnectTimeout(), TimeUnit.SECONDS)
                .writeTimeout(configuration.getWriteTimeout(), TimeUnit.SECONDS)
                .readTimeout(configuration.getReadTimeout(), TimeUnit.SECONDS)
                .build();
        configuration.setOkHttpClient(okHttpClient);
        
        // 3.创建retrofit2的API服务
        ChatGlmApi chatGlmApi = new Retrofit.Builder()
                .baseUrl(configuration.getApiHost())
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(JacksonConverterFactory.create())
                .build().create(ChatGlmApi.class);
        configuration.setChatGlmApi(chatGlmApi);
        
        // 4.创建执行器
        HashMap<Model, Executor> executorMap = configuration.createExecutorMap();
        
        return new ChatGlmSessionImpl(configuration, executorMap);
    }

}
